<template>
	<el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="24" class="mb20">
					<el-form-item label="分类级别" prop="categoryLevel">
						<el-radio-group v-model="categoryLevel">
							<el-radio border :label="1">一级分类</el-radio>
							<el-radio border :label="2">二级分类</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="分类类型" prop="categoryLevel">
						<el-radio-group v-model="form.categoryType">
							<el-radio border label="1">支出</el-radio>
							<el-radio border label="2">收入</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="分类名称" prop="name">
						<el-input v-model="form.name" placeholder="请输入分类名称" />
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="图标" prop="icon">
            <IconSelector v-model="form.icon" :title="''"/>
<!--            <el-select v-model="form.icon" placeholder="Select" style="width: 360px">
              <el-option
                  v-for="name in classNames"
                  :key="name"
                  :label="name"
                  :value="name"
              >
                <span style="float: left">
                  	<svg class="icon" aria-hidden="true" font-size="32">
                      <use :xlink:href="'#'+name"></use>
                    </svg>
                </span>
                <span
                    style="
          float: right;
          color: var(&#45;&#45;el-text-color-secondary);
          font-size: 13px;
        "
                >
        {{ name }}
      </span>
              </el-option>
            </el-select>-->
						<!--        <el-input v-model="form.icon" placeholder="请输入图标"/>-->

					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20" v-if="categoryLevel === 2">
					<el-form-item label="父级分类ID" prop="parentId">
						<el-input v-model="form.parentId" placeholder="请输入父级分类ID" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="AccCategoriesDialog">
import { useMessage } from '/@/hooks/message';
import { addObj, getObj, putObj } from '/@/api/account/accCategories';

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/IconSelector/index.vue'));

const emit = defineEmits(['refresh']);

// 定义变量内容
const iconFontUrl = '/@/assets/js/importSvg.js';
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const categoryLevel = ref(1);
const classNames = ref([]);
// 定义字典

// 提交表单数据
const form = reactive({
	id: '',
	userId: '',
	name: '',
	icon: 'iconfont icon-kaguanli',
	parentId: 0,
	categoryType: "1",
});

// 定义校验规则
const dataRules = ref({});

// 打开弹窗
const openDialog = (id: string) => {
	visible.value = true;
	form.id = '';

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});

	// 获取accCategories信息
	if (id) {
		form.id = id;
		getAccCategoriesData(id);
	}
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 初始化表单数据
const getAccCategoriesData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj({ id: id })
		.then((res: any) => {
			Object.assign(form, res.data[0]);
      console.log('form', form)
		})
		.finally(() => {
			loading.value = false;
		});
};

// 加载SVG图标
const loadSvgSymbols = async (url: string) => {
	try {
		const response = await import(url);
		const symbolIds = response.default.icon.match(/<symbol id="([^"]+)"/g)?.map((tag: string) => tag.match(/id="([^"]+)"/)[1]);
		return symbolIds || [];
	} catch (error) {
		console.error('Failed to load SVG symbols:', error);
		return [];
	}
};

const getIconNames = async (url: string) => {
	return await loadSvgSymbols(url);
};

onMounted(async () => {
  classNames.value = await getIconNames(iconFontUrl);
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>
